package com.ks.service;

import com.ks.base.BaseService;
import com.ks.dao.*;
import com.ks.entity.*;
import com.ks.util.RandomUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("paperService")
public class PaperService<T> extends BaseService<T> {
    private final static Logger log = Logger.getLogger(PaperService.class);

    @Autowired
    private PaperDao<T> dao;
    @Autowired
    private ContentDao<T> contentDao;
    @Autowired
    private ContentQuestionDao<T> contentQuestionDao;
    @Autowired
    private DepositoryDao<T> depositoryDao;
    @Autowired
    private PaperDao<T> paperDao;
    @Autowired
    private PaperQuestiontypeDao<T> paperQuestiontypeDao;
    @Autowired
    private QuestionDao<T> questionDao;
    @Autowired
    private QuestionCopyDao<T> questionCopyDao;
    @Autowired
    private PaperQuestionDao<T> paperQuestionDao;
    @Autowired
    private QuestiontypeDao<T> questiontypeDao;
    @Autowired
    private UserDao<T> userDao;

    public PaperDao<T> getDao() {
        return dao;
    }

    public int queryQuestionTypeCount(Object o) {
        return dao.queryQuestionTypeCount(o);
    }


    /**
     * 删除试卷    删除试卷表及其关联表
     *
     * @param o
     */
    @Transactional
    public void delpaper(Object o) {

        //删除paper表
        dao.delete(o);

    }

    /**
     * 保存修改试卷
     *
     * @param list
     */
    @Transactional
    public Map<String, Object> saveOrEditPaper(List<PaperQuestiontype> list) {
    	
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        ApplicationContext ac = null;
        PaperQuestion paperQuestion = null;
        Paper paper = null;
        Map<String, Object> map = new HashMap<>();
        //t_ks_paper_questiontype表添加记录
        for (PaperQuestiontype entity : list) {
            if (entity.getId() == null || StringUtils.isBlank(entity.getId().toString())) {
                paperQuestiontypeDao.add(entity);
            } else {
                paperQuestiontypeDao.updateBySelective(entity);
            }
            //paper_question表
            //试题类型
            Integer typeid = entity.getQuestiontype_id();
            //该类型试题数量
            Integer count = Integer.parseInt(entity.getCount());
            // 难题比例
            Integer rate = Integer.parseInt(entity.getRate());
            //难题数量
            int diffCount = rate * count / 100;
            //易题比例
            Integer easyrate = Integer.parseInt(entity.getEasyrate());
            //简单题数量
            int easyCount = count*easyrate/100;
            paper = (Paper) dao.queryById(entity.getPaper_id());
            String[] conIds = paper.getExtend().split(",");
            map.put("typeId", typeid);
            map.put("conIds",conIds);
            map.put("type", 1);
            List<Question> qdlist = questionDao.findListByIdType(map);
            String msg = "数量不足请重新选择题库";
            if (diffCount < qdlist.size()) {
                //t_ks_paper_question表添加记录 难题
                int[] setdiff = RandomUtils.getDifferentRandom(diffCount, qdlist.size());
                for (Integer i : setdiff) {
                    ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                    paperQuestion = (PaperQuestion) ac.getBean("paperQuestion");
                    Question question = (Question) qdlist.get(i);
                    paperQuestion.setQuestion_id(question.getId());
                    paperQuestion.setPaper_id(entity.getPaper_id());
                    paperQuestionDao.add(paperQuestion);
                }
            } else {
                resultMap.put("code", 1);
                msg = "难题" + msg;
                resultMap.put("Msg", msg);
                return resultMap;
            }
            map.put("type", 3);
            List<Question> qslist = questionDao.findListByIdType(map);
            if (easyCount < qslist.size()) {
                //t_ks_paper_question表添加记录 简单题
                int[] seteasy = RandomUtils.getDifferentRandom(easyCount, qslist.size());
                for (Integer i : seteasy) {
                    ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                    paperQuestion = (PaperQuestion) ac.getBean("paperQuestion");
                    Question question = (Question) qslist.get(i);
                    paperQuestion.setQuestion_id(question.getId());
                    paperQuestion.setPaper_id(entity.getPaper_id());
                    paperQuestionDao.add(paperQuestion);
                }
            } else {
                resultMap.put("code", 1);
                msg = "简单题" + msg;
                resultMap.put("Msg", msg);
                return resultMap;
            }
            map.put("type", 2);
            List<Question> qmlist = questionDao.findListByIdType(map);
            //中间难度题数量
            int midCount = count - easyCount - diffCount;
            if (midCount < qmlist.size()) {
                //t_ks_paper_question表添加记录 简单题
                int[] seteasy = RandomUtils.getDifferentRandom(midCount, qmlist.size());
                for (Integer i : seteasy) {
                    ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                    paperQuestion = (PaperQuestion) ac.getBean("paperQuestion");
                    Question question = (Question) qmlist.get(i);
                    paperQuestion.setQuestion_id(question.getId());
                    paperQuestion.setPaper_id(entity.getPaper_id());
                    paperQuestionDao.add(paperQuestion);
                }
            } else {
                resultMap.put("code", 1);
                msg = "中间题" + msg;
                resultMap.put("Msg", msg);
                return resultMap;
            }
            resultMap.put("Msg", msg);
        }
        return resultMap;
    }

    /**
     * 备份试卷
     *
     * @param paperid
     */
    @Transactional
    public void paperCopy(String paperid) {
        //发布试卷
        Map<String, Object> paperMap = new HashMap<>();
        paperMap.put("id", paperid);
        paperMap.put("status", "1");
        dao.updateBySelective(paperMap);
        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
        PaperQuestion pq = (PaperQuestion) ac.getBean("paperQuestion");
        pq.setPaper_id(Integer.parseInt(paperid));
        List<T> copylist = paperQuestionDao.queryList(pq);
        Question question = (Question) ac.getBean("question");
        for (T t : copylist) {
            PaperQuestion entity = (PaperQuestion) t;
            // 查找question表
            question = (Question) questionDao.queryById(entity.getQuestion_id());
            question.setId(null);
            questionCopyDao.add(question);
            entity.setQuestion_copy_id(question.getId());
            paperQuestionDao.updateBySelective(entity);
        }
    }

    public Map<String, Object> deployPaper(Paper entity) {

        Map<String, Object> context = new HashMap<>();
        List<Map<String, Object>> list = contentDao.queryContentDetail(null);
        context.put("list", list);
        if (entity.getId() == null || StringUtils.isBlank(entity.getId().toString())) {
            context.put("flag", "add");
        } else {
            Paper paper = (Paper) dao.queryById(entity);
            context.put("flag", "edit");
            context.put("paper", paper);
            Map<String, Object> map = new HashMap<>();
            // 单选题数量
            map.put("paper_id", paper.getId());
            map.put("questiontype_id", 1);
            List<T> single = paperQuestiontypeDao.queryList(map);
            if (single.size()>0) {
                    context.put("singleEntity", single.get(0));
            }

            // 多选题数量
            map.put("questiontype_id", 2);
            List<T> muti = paperQuestiontypeDao.queryList(map);
            if (muti.size()>0) {
                context.put("mutiEntity", muti.get(0));
            }

            // 判断题数量
            map.put("questiontype_id", 3);
            List<T> judge = paperQuestiontypeDao.queryList(map);
            if (judge.size()>0) {
                context.put("judgeEntity", judge.get(0));
            }
            context.put("paperid", paper.getId());

            if (single.size() == 0 && muti.size() == 0 && judge.size() == 0) {
                context.put("flag", "add");
            }
        }
        return context;
    }

    public Map<String, Object> issuePage(String paperid) {

        Map<String, Object> map = new HashMap<>();
        Paper entity = (Paper) paperDao.queryById(paperid);
        T t = depositoryDao.queryById(entity.getDepository_id());
        Depository depository = (Depository) t;
        map.put("depositoryname", depository.getName());
        User creater = (User) userDao.queryById(entity.getCreater());
        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
        PaperQuestiontype paperQuestiontype = (PaperQuestiontype) ac.getBean("paperQuestiontype");
        paperQuestiontype.setPaper_id(entity.getId());
        List<T> list = paperQuestiontypeDao.queryList(paperQuestiontype);
        map.put("paperid", paperid);
        map.put("title", "编辑试卷");
        map.put("paper", entity);
        map.put("questiontype", list);
        //试卷作者
        map.put("creater", creater.getName());
        return map;
    }

    public Map<String, Object> pagePreview(String paperid) {
        Map<String, Object> context = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        Paper paper = (Paper) dao.queryById(paperid);
        User creater = (User) userDao.queryById(paper.getCreater());
        context.put("paper", paper);
        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
        PaperQuestion paperQuestion = (PaperQuestion) ac.getBean("paperQuestion");
        paperQuestion.setPaper_id(paper.getId());
        List<T> idlist = paperQuestionDao.queryList(paperQuestion);
        int[] arr = new int[idlist.size()];
        for (int i = 0; i < idlist.size(); i++) {
            PaperQuestion entity = (PaperQuestion) idlist.get(i);
            arr[i] = entity.getQuestion_copy_id();
        }

        map.put("questiontype_id",1);
        map.put("ids",arr);
        List<QuestionCopy> singlelist = questionCopyDao.queryListByPaper(map);
        map.put("questiontype_id",2);
        List<QuestionCopy> mutilist = questionCopyDao.queryListByPaper(map);

        map.put("questiontype_id",3);
        List<QuestionCopy>  judgelist = questionCopyDao.queryListByPaper(map);
        Map<String, Object> mapScore = new HashMap<>();
        map.put("paper_id",paperid);
        map.put("quetiontype_id",1);
        List<PaperQuestiontype> singlets = (List<PaperQuestiontype>) paperQuestiontypeDao.queryList(map);
        if (singlets.size()>0){
            context.put("singlescore",singlets.get(0).getScore());
        }
        map.put("paper_id",paperid);
        map.put("quetiontype_id",1);
        List<PaperQuestiontype> mutits = (List<PaperQuestiontype>) paperQuestiontypeDao.queryList(map);
        if (mutits.size()>0){
            context.put("mutiscore",mutits.get(0).getScore());
        }
        map.put("paper_id",paperid);
        map.put("quetiontype_id",1);
        List<PaperQuestiontype> judgets = (List<PaperQuestiontype>) paperQuestiontypeDao.queryList(map);
        if (judgets.size()>0){
            context.put("judgescore",judgets.get(0).getScore());
        }
        context.put("singlelist", singlelist);
        context.put("singlecount", singlelist.size());
        context.put("mutilist", mutilist);
        context.put("muticount", mutilist.size());
        context.put("judgelist", judgelist);
        context.put("judgecount", judgelist.size());
        context.put("creater", creater.getName());
        return context;
    }

    public Map<String, Object> viewOrEditPage(String paperid) {
        Map<String, Object> context = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        Paper paper = (Paper) dao.queryById(paperid);
        User creater = (User) userDao.queryById(paper.getCreater());
        context.put("paper", paper);
        //1单选题
        map.put("paperid",paperid);
        map.put("questiontype_id",1);
        List<Question> singlelist = questionDao.queryPaperQuestions(map);
        //2多选题
        map.put("questiontype_id",2);
        List<Question> mutilist = questionDao.queryPaperQuestions(map);
        //3判断题
        map.put("questiontype_id",3);
        List<Question> judgelist = questionDao.queryPaperQuestions(map);
        context.put("singlelist", singlelist);
        context.put("singlecount", singlelist.size());
        context.put("mutilist", mutilist);
        context.put("muticount", mutilist.size());
        context.put("judgelist", judgelist);
        context.put("judgecount", judgelist.size());
        context.put("creater", creater.getName());
        return context;
    }

    public void saveOrEditPaperHand(List<PaperQuestiontype> list) {
        //t_ks_paper_questiontype表添加记录
        for (PaperQuestiontype entity : list) {
            if (entity.getId() == null || StringUtils.isBlank(entity.getId().toString())) {
                paperQuestiontypeDao.add(entity);
            } else {
                paperQuestiontypeDao.updateBySelective(entity);
            }
        }
    }
    @Transactional
    public Map<String, Object> toCheckQuestion(String conId, String questiontypeId, String paperid,String score) {
        Map<String, Object> contextMap = new HashMap<>();
        PaperQuestiontype paperQuestiontype = new PaperQuestiontype();
        paperQuestiontype.setPaper_id(Integer.parseInt(paperid));
        paperQuestiontype.setQuestiontype_id(Integer.parseInt(questiontypeId));
        paperQuestiontype.setScore(score);
        paperQuestiontypeDao.deleteByPaperid(paperQuestiontype);
        paperQuestiontype.setScore(score);
        paperQuestiontypeDao.add(paperQuestiontype);
        Map<String, Object> paperMap = new HashMap<>();
        paperMap.put("paper_id", paperid);
        List<PaperQuestion> paperQuestionlist = (List<PaperQuestion>) paperQuestionDao.queryList(paperMap);
        List<PaperQuestion> list = new ArrayList<>();
        for (PaperQuestion paperQuestion : paperQuestionlist) {
            Question question = (Question) questionDao.queryById(paperQuestion.getQuestion_id());
            if(questiontypeId.equals(String.valueOf(question.getQuestiontype_id()))) {
                list.add(paperQuestion);
            }
        }
        Paper paper = (Paper) paperDao.queryById(paperid);
        contextMap.put("paperQuestions", list);
        List<Object> questionId = new ArrayList<>();
        for (PaperQuestion paperQuestion : list) {
            questionId.add(paperQuestion.getQuestion_id());
        }
        contextMap.put("questionId",questionId);
        contextMap.put("paper", paper);
        List<String> strlist = new ArrayList<>();
        //根据知识点 试题类型查找题目
        Map<String, Object> questionMap = new HashMap<>();
        questionMap.put("str", conId.split(","));
        questionMap.put("questiontype_id", questiontypeId);
        questionMap.put("pagefrom", 0);
        questionMap.put("pagesize", 5);
        List<Map<String, Object>> allQuestions = contentQuestionDao.findListByContentids(questionMap);

        contextMap.put("resultList", allQuestions);
        return contextMap;
    }

    public void updatePaperQuestions(String paperid, String qutypeid) {
        PaperQuestiontype paperQuestiontype = new PaperQuestiontype();
        paperQuestiontype.setPaper_id(Integer.parseInt(paperid));
        paperQuestiontype.setQuestiontype_id(Integer.parseInt(qutypeid));
        Map<String, Object> countMap = new HashMap<>();
        //根据paperid 和 typeid 查找试题
        countMap.put("questiontype_id",qutypeid);
        countMap.put("paper_id",paperid);
        List<PaperQuestion> paperQuestions = paperQuestionDao.queryByPaperidAndTypeId(countMap);
        paperQuestiontype.setCount(paperQuestions.size()+"");
        paperQuestiontypeDao.updateByPaperIdAndTypeId(paperQuestiontype);
    }

    public Map<String, Object> printPreview(String id) {
        Map<String, Object> context = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        Paper paper = (Paper) dao.queryById(id);
        User creater = (User) userDao.queryById(paper.getCreater());
        context.put("paper", paper);
        //1单选题
        map.put("paperid",id);
        map.put("questiontype_id",1);
        List<Question> singlelist = questionDao.queryPaperQuestions(map);
        //2多选题
        map.put("questiontype_id",2);
        List<Question> mutilist = questionDao.queryPaperQuestions(map);
        //3判断题
        map.put("questiontype_id",3);
        List<Question> judgelist = questionDao.queryPaperQuestions(map);
        context.put("singlelist", singlelist);
        context.put("singlecount", singlelist.size());
        context.put("mutilist", mutilist);
        context.put("muticount", mutilist.size());
        context.put("judgelist", judgelist);
        context.put("judgecount", judgelist.size());
        context.put("creater", creater.getName());
        return context;
    }

    public Map<String, Object> toCheckQuestionAjax(String paperid,String typeId, String conId, String page_num, String page_size) {
        Map<String, Object> finalresultMap = new HashMap<>();
        String msg = "操作成功！";
        Integer status = 1;
        Integer offset = 0;
        Integer pageSize = 0;
        if (StringUtils.isNotBlank(page_num) && StringUtils.isNotBlank(page_size)) {
            Integer pageNum = Integer.parseInt(page_num);
            pageSize = Integer.parseInt(page_size);
            if (pageNum > 1) {
                offset = (pageNum - 1) * pageSize;
            } else {
                offset = 0;
            }
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("conId", conId);
        dataMap.put("typeId", typeId);
        dataMap.put("offset", offset);
        dataMap.put("page_size", pageSize);

        // 根据typeId查询试题类型
        Questiontype qt = (Questiontype) questiontypeDao.queryById(typeId);
        // 根据章节id查询章节内容
        Content cont = (Content) contentDao.queryById(conId);
        // 根据章节id和题类型id查询题目
        List<Question> resultList =  questionDao.findByTypeIdAndConId(dataMap);
        Map<String, Object> map = new HashMap<>();
        //跟据paperid查找试题
        map.put("paper_id",paperid);
        String sels = "";
        List<PaperQuestion> ts = (List<PaperQuestion>) paperQuestionDao.queryList(map);
        for (PaperQuestion t : ts) {
            sels = sels + t.getQuestion_id() + ",";
        }
        finalresultMap.put("status", status);
        finalresultMap.put("msg", msg);
        finalresultMap.put("resultList", resultList);
        finalresultMap.put("sels", sels);
        return finalresultMap;
    }

    public List<Paper> findAll(Object o){
       return dao.findAllDesc(o);
    }

    public void updatePaperQuestionsAjax(String type, String paperid, String questionid) {
        PaperQuestion  paperQuestion = new PaperQuestion();
        paperQuestion.setPaper_id(Integer.parseInt(paperid));
        paperQuestion.setQuestion_id(Integer.parseInt(questionid));
        if ("add".equals(type)) {
            paperQuestionDao.add(paperQuestion);
        } else {
            paperQuestionDao.delEntity(paperQuestion);
        }

    }

    public Map<String, Object> deployPaperAuto(Paper entity) {

        Map<String, Object> context = new HashMap<>();
        List<Map<String, Object>> list = contentDao.queryContentDetail(null);
        context.put("list", list);
        if (entity.getId() == null || StringUtils.isBlank(entity.getId().toString())) {
            context.put("flag", "add");
        } else {
            Paper paper = (Paper) dao.queryById(entity);
            context.put("flag", "edit");
            context.put("paper", paper);
            Map<String, Object> map = new HashMap<>();
            // 单选题数量
            map.put("paper_id", paper.getId());
            map.put("questiontype_id", 1);
            List<T> single = paperQuestiontypeDao.queryList(map);
            context.put("singlelist", single);
            // 多选题数量
            map.put("questiontype_id", 2);
            List<T> muti = paperQuestiontypeDao.queryList(map);
            context.put("mutilist", muti);
            // 判断题数量
            map.put("questiontype_id", 3);
            List<T> judge = paperQuestiontypeDao.queryList(map);
            context.put("paperid", paper.getId());
            context.put("judgelist", judge);
            if (single.size() == 0 && muti.size() == 0 && judge.size() == 0) {
                context.put("flag", "add");
            }
        }
        return context;
    }
}
